<template>
  <div class="record-com shade-mask"
    @mousemove="movingSlide" 
    @mouseup="stopSlideMoving" 
    @touchmove="movingSlide" 
    @touchend="stopSlideMoving" 
    @click="stopDragByClick" 
    v-show="is_show">
    <div class="bgfff tip-main">
      <p class="tcenter title">
        {{title}}
        <i class="close-icon" @click="closeRecordComponent"></i>
      </p>
      <div class="slide-module-com">
        <div class="slide-box">
          <p class="progress-con" ref="progressBar" @click="clickProgress">
            <span class="progress-bg" :style="{width:slide_left+'%'}"></span>
            <span class="slide-block" 
              @touchstart="moveSlideStart" 
              @mousedown="moveSlideStart" 
              :style="{left:slide_left+'%'}"></span>
          </p>
        </div>
        <ul class="time-count-com">
          <li>{{cur_time|formatPlayTime}}</li>
          <li>{{max_time|formatPlayTime}}</li>
        </ul>
        <p class="audio-line"></p>
        <div class="handle-box">
          <div class="audio-handle-btn" :class="{'audio-play':!is_play,'audio-pause':is_play}" @click="handleAudioPlay"></div>
        </div>
      </div>
      <div class="origin-demo">
        <div>
          <p>原生播放器：</p>
          <button @click="getRecord">获取</button>
        </div>
        <div>
          <audio :src="record" 
            @error="loadError"
            @loadedmetadata="loadedMetadata"
            @timeupdate="timeUpdate" 
            @ended="ended" 
            @play="play" 
            @pause="pause"
            type="audio/wav"
            controls
            ref="audioEl"></audio>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  export default {
    name:"Record",
    props: {
      title:{
        type:String,
        default:"音频"
      },
      is_show:{
        type:Boolean,
        default:false
      }
    },
    model:{
      prop:"is_show",
      event:"change",
    },
    data(){
      return{
        record: '/static/audio/SoundTest.wav',
        is_error:false,
        max_time:0, //最大播放时间
        cur_time:0, //当前播放时间
        slide_left:0, //滑块位置
        is_dragging:false, //判断是否拖拽
        is_play:false, //是否播放中
      }
    },
    methods:{
      //拖拽修正
      stopDragByClick(){
        if(this.is_dragging){
          this.is_dragging = false;
        }
      },
      loadError(e){
        this.is_error = true;
        console.log("loadError",e)
      },
      moveSlide(e){
        // console.log(e);
      },
      //开始拖拽
      moveSlideStart(e){
        this.is_dragging = true;
        console.log(e)
        if(!this.is_error){
          this.$refs.audioEl.pause();
        }
      },
      // 拖拽中
      movingSlide(e){
        if(!this.is_error){
          if(this.is_dragging){
            this.posHandle(e);
          }
        }
      },
      //结束拖拽（默认播放）
      stopSlideMoving(e){
        if(!this.is_error){
          if(this.is_dragging){
            console.log("stop_:",e)
            this.posHandle(e,true);
            let au = this.$refs.audioEl;
            this.is_dragging = false;
            console.log("进度",this.cur_time)
            if(this.slide_left<100){//偶现拖动以后播放停止
              au.play();
            }
          }
        }
      },
      //点击进度条（默认播放）
      clickProgress(e){
        if(!this.is_error){
          this.posHandle(e,true);
          if(this.slide_left<100){
            this.$refs.audioEl.play();
          }
        }else{
          // this.toast("录音加载失败")
        }
      },
      //移动事件封装
      posHandle(e,handle){
        e = e||window.event;
        let p = this.$refs.progressBar;
        let au = this.$refs.audioEl;
        let w = p.clientWidth;
        let pl = p.getBoundingClientRect().left;
        let cx = e.x||e.clientX||(e.touches.length&&e.touches[0].clientX)||(e.changedTouches.length&&e.changedTouches[0].clientX);
        let d = cx - pl;
        // console.log("位置差_:",d,au.readyState);
        if(d<0){//最小
          if(handle){au.currentTime = 0;}
          this.slide_left = 0;
        }else if(d>w){//最大
          if(handle){au.currentTime = this.max_time;}
          this.slide_left = 100;
        }else{//在中间(有效值)
          if(handle){au.currentTime = this.max_time*d/w;}
          this.slide_left = d*100/w;
        }
      },
      //开始播放
      play(e){
        this.is_play = true;
        console.log("_start_")
      },
      pause(e){
        console.log("_pause_",this.is_dragging)
        if(!this.is_dragging){
          this.is_play = false;
        }
      },
      //播放结束
      ended(e){
        this.is_play = false;
        console.log("_ended_")
      },
      //浏览器获取完媒体的时长和字节数
      loadedMetadata(e){
        // console.log(e);
        let el = this.$refs.audioEl;
        // console.log("音频时长_:",el.duration);
        this.max_time = el.duration;
      },
      //播放时间更新
      timeUpdate(e){
        let el = this.$refs.audioEl;
        // console.log("播放时长_:",el.currentTime);
        this.slide_left = el.currentTime*100/this.max_time;
        // console.log("滑块位置",this.slide_left)
        this.cur_time = el.currentTime;
        // console.log(e);
      },
      //播放控制
      handleAudioPlay(){
        if(!this.is_error){
          let au = this.$refs.audioEl;
          console.log("au.readyState_:",au.readyState)
          if(this.is_play){
            au.pause();
          }else{
            au.play();
          }
        }else{
          // this.toast("录音加载失败")
        }
      },
      //关闭
      closeRecordComponent(){
        if(!this.is_error){
          this.$refs.audioEl.pause();
          setTimeout(()=>{
            this.$refs.audioEl.currentTime = 0;
          },300)
        }
        this.$emit('change',false)
      },
      getRecord(){
        // this.$http.get("http://172.20.102.27:8080/getkeyAudio",{
        //   responseType: 'blob'
        // }).then(d=>{
        //   let f = d.data; 
        //   let blob = new Blob([f]);
        //   console.log("blob_:",blob);
        //   let href = URL.createObjectURL(blob);
        //   console.log("blob_href:",href)
        //   this.record = href;
        //   /**
        //    * 文件直接下载
        //    */
        //   // let downloadElement = document.createElement("a");
        //   // let href = window.URL.createObjectURL(blob); //创建下载的链接
        //   // downloadElement.href = href;
        //   // downloadElement.download = "test.wav"; //下载后文件名
        //   // document.body.appendChild(downloadElement);
        //   // downloadElement.click(); //点击下载
        //   // document.body.removeChild(downloadElement); //下载完成移除元素
        //   // window.URL.revokeObjectURL(href); //释放掉blob对象
        // }).catch(err=>{
        //   console.log("Error_:",err)
        // })
      }
    },
    filters:{
      formatPlayTime(val){
        // console.log("formatCurTime_:",val)
        if(val){
          let temp = val;
          let h = Math.floor(temp/60/60);
          if(h>0){
            temp = temp - h*60*60; 
          }
          h = h>9?h:("0"+h)
          let m = Math.floor(temp/60);
          if(m>0){
            temp = temp - m*60; 
          }
          m = m>9?m:("0"+m)
          let s = Math.floor(temp);
          s = s>9?s:("0"+s)
          return [h,m,s].join(":")
        }else{
          return "00:00:00"
        }
      }
    }
  }
</script>
<style lang="less" scoped>
@main-color:rgba(30,124,200,1);
.record-com{
  // height:6rem;
}
.shade-mask{
  position:fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left:0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 100;
  .tip-main{
    background-color:#fff;
    position: fixed;
    top: 50%;
    left: 50%;
    width: 80%;
    transform: translate(-50%,-50%);
    border-radius: .12rem;
    .title {
      padding-left:0.12rem;
      background:@main-color;
      height:1rem;
      font-size:0.4rem;
      line-height:1rem;
      color:#fff;
      border-top-left-radius:.12rem;
      border-top-right-radius:.12rem;
      position:relative;
      .close-icon{
        display: inline-block;
        width:0.4rem;
        height:0.4rem;
        position:absolute;
        top:50%;
        transform:translateY(-50%);
        right:0.3rem;
        background:url("../../assets/img/audio/dialog_close_icon.png");
        background-size:cover;
        transition: opacity 0.1s;
        &:active{
          opacity: 0.7;
        }
      }
    }
  }
}
//录音样式文件设置
.slide-module-com{
  padding:0.6rem 0.3rem 0.3rem 0.3rem;
  .slide-box{
    user-select:none;
    margin-bottom:0.3rem;
    .progress-con{
      width:100%;
      height:0.1rem;
      background-color:rgba(30,124,200,0.3);
      border-radius:0.02rem;
      position:relative;
      .progress-bg{
        display:block;
        height:100%;
        border-radius:0.02rem;
        background-color:rgba(30,124,200,1);
        width:0;
      }
      .slide-block{
        width:0.3rem;
        height:0.3rem;
        border-radius:50%;
        background-color:rgba(30,124,200,1);
        display:block;
        position:absolute;
        top:-0.1rem;
        cursor: grab;
        transform:translateX(-50%);
      }
    }
  }
  .time-count-com{
    display: flex;
    justify-content: space-between;
    li{
      white-space: nowrap;
      font-size:0.3rem;
    }
  }
  .audio-line{
    margin-top:0.3rem;
    height:0.07rem;
    background-color:rgb(232, 232, 232);
  }
  .handle-box{
    display:flex;
    justify-content: center;
    margin-top:0.3rem;
  }
  .audio-handle-btn{
    width:1rem;
    height:1rem;
    // border-radius:50%;
    background-origin:top left;
    background-size:100%;
    background-repeat:no-repeat;
    transition:opacity 0.1s;
    &:active{
      opacity: 0.7;
    }
  }
  .audio-play{
    background-image:url('../../assets/img/audio/voice_play_icon.png');
  }
  .audio-pause{
    background-image:url('../../assets/img/audio/voice_stop_icon.png');
  }
}
.origin-demo{
  padding-bottom:0.2rem;
  >div{
    display:flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
